#include "pfilelisttablemodel.h"

#include "QtDebug.h"
#include "qappwidget.h"

PFileListTableModel::PFileListTableModel( PFileList *file_list , QObject *parent ):
    QAbstractTableModel(parent),
    m_file_list(file_list)
{
}

int PFileListTableModel::rowCount(const QModelIndex &parent) const
{
    return(m_file_list->sizeOf());
}

int PFileListTableModel::columnCount(const QModelIndex &parent) const
{
    return 6;
}

QVariant PFileListTableModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
         return QVariant();

    if (index.row() < 0)
         return QVariant();

    if (index.row() >= m_file_list->sizeOf())
         return QVariant();

    if (index.column() < 0)
         return QVariant();

    if (index.column() >= 6)
        return QVariant();

    PFileItem pf;
    pf = m_file_list->getAt(index.row());

    if (role == Qt::DisplayRole || role == Qt::EditRole)
    {
        switch (index.column())
        {
        case 0: // ID
            return QVariant(QSTR(pf.getKeyStr()));
        case 1: // DESCRIZIONE
            return QVariant(QSTR(pf.getModuleFileName()));
        case 2: // DESCRIZIONE
            return QVariant(pf.existFile());
        case 3: // TIPO DI MODULO
            return QVariant(QSTR(PFileItem::moduleObjName(pf.getModuleType())));
        case 4: // NOME DEL FILE COLLEGATO
            return QVariant(QSTR(pf.getDescr()));
        case 5: // CORRENTE
            return QVariant(pf.isModuleCurrent());
        default:
            return QVariant();
        }
    }
    if (role == Qt::BackgroundRole)
    {
        switch (index.column())
        {
        case 0: // ID
            return QVariant(QColor(Qt::lightGray));
        case 1: // DESCRIZIONE
            return QVariant(QColor(Qt::lightGray));
        case 2: // DESCRIZIONE
            return QVariant(QColor(Qt::lightGray));
        case 3: // TIPO DI MODULO
            return QVariant(QColor(Qt::lightGray));
        default:
            return QVariant();
        }
    }

    if (role == Qt::UserRole)
    {
        return QVariant::fromValue(pf);
    }

    if (role == Qt::TextAlignmentRole)
    {
        return QVariant(Qt::AlignCenter|Qt::AlignVCenter);
    }

    if (role == Qt::TextColorRole && pf.isModuleCurrent())
        return QVariant(QColor(Qt::red));

    return QVariant();
}

QVariant PFileListTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role != Qt::DisplayRole)
        return QVariant();

    if (orientation == Qt::Horizontal)
       switch (section)
       {
       case 0:
           return tr("Id");
       case 1:
           return tr("nome file");
       case 2:
           return tr("esiste");
       case 3:
           return tr("tipo modulo");
       case 4:
           return tr("descrizione");
       case 5:
           return tr("corrente");
       }
    else
        return QString("n.%1").arg(section+1);
}

bool PFileListTableModel::insertRows(int position, int rows, const QModelIndex &parent )
{
    Q_UNUSED(parent);
    beginInsertRows(QModelIndex(), position, position+rows-1);
    m_file_list->insertAt(position, rows);
    endInsertRows();
    return true;
}

bool PFileListTableModel::removeRows(int position, int rows, const QModelIndex &parent )
{
    Q_UNUSED(parent);
    beginRemoveRows(QModelIndex(), position, position+rows-1);

    for (int row=0; row < rows; ++row)
    {
        // Rimuovo il file collegato definitivamente
        m_file_list->valueAt(position).removeModuleFile();

        // Rimuovo l'elemento della lista
        m_file_list->remove(position);
    }

    // Se Cancello l'ultimo elemento della lista azzero il contatore
    if (m_file_list->sizeOf() == 0) PFileList::setLastId(0);

    endRemoveRows();
    return true;
}

bool PFileListTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (index.isValid() && role == Qt::EditRole)
    {
        switch (index.column())
        {
        case 0: // ID
            break;
        case 1: // NOME FILE
            break;
        case 2: // ESISTE
            break;
        case 3: // TIPO DI MODULO
            break;
        case 4: // DESCRIZIONE
            {
                string descr = value.toString().toStdString();
                qDebug()<<"setto la descrizione = "<<QSTR(descr);
                m_file_list->setDescr(index.row(),descr);
                break;
            }
        case 5: // CORRENTE
            {
                ExaModuleErr err;
                err = m_file_list->setModuleCurrent(index.row(),value.toBool());
                if (err != EXA_MODULE_ERR_OK)
                {
                    QAppWidget::errMsgBox(err,m_file_list->getAt(index.row()));
                    return false;
                }
                break;
            }
        }
        // m_file_list->valueAt(index.row()) = item;
        qDebug()<<"Editato cella ...........";
        qDebug() << m_file_list->getAt(index.row());
        emit( dataChanged( index, index ) );
        return true;
    }
    else if (index.isValid() && role == Qt::UserRole)
    {
        int row = index.row();
        qDebug()<<"PFileListTableModel::setData inserisco alla riga "<<row;
        PFileItem pf = value.value< PFileItem >();
        m_file_list->rename(row,pf.getKeyStr(),pf.getDescr());
        m_file_list->valueAt(row) = pf;
        QModelIndex i = this->index(row,5);
        emit( dataChanged( index, i ) );
        return true;
    }
    else
        return false;
}

void PFileListTableModel::updateWEDChange(void)
{
    reset();
    emit( dataChanged(QModelIndex(),QModelIndex()) );
}

void PFileListTableModel::updateWEDChangeWReset(void)
{
    emit( dataChanged(QModelIndex(),QModelIndex()) );
}

void PFileListTableModel::append ( ExaModuleObj m )
{
    // Inserisco una linea vuota
    insertRows(rowCount(),1);

    // Nuovo elemento da inserire
    PFileItem item;

    // Costruisco la chiave unica
    int nb = PFileList::newId();
    QString key = QString(QSTR(PFileItem::moduleObjName(m)) + " %1").arg(nb);
    item.setKeyStr(key.toStdString());
    item.setDescr("<...>");

    // Costruisco il nome del file
    QString file_name = QString("DAT%1.mod").arg(nb);
    item.setModuleFileName(file_name.toStdString());

    // Setto il tipo di modulo
    item.setModuleType(m);

    // Inserisco l'elemento dove l'ho aggiunto
    qDebug() << item;
    QModelIndex i = index(rowCount()-1,0);
    setData(i,QVariant::fromValue(item),Qt::UserRole);
}

Qt::ItemFlags PFileListTableModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return Qt::ItemIsEnabled;

    if (index.column() == 4 && m_file_list->isModuleCurrent(index.row()))
    {
        return QAbstractTableModel::flags(index) | Qt::ItemIsEditable;
    }
    if (index.column() == 5)
    {
        return QAbstractTableModel::flags(index) | Qt::ItemIsEditable;
    }
    return QAbstractTableModel::flags(index);
}
